// components/image-sort/index.ts
Component({
  properties: {
    images: {
      type: Array,
      value: []
    },
    deletable: {
      type: Boolean,
      value: true
    },
    maxCount: {
      type: Number,
      value: 9
    }
  },
  data: {
    draggingIndex: -1,
    tempImages: [] as any[],
    startX: 0,
    startY: 0,
    currentTargetIndex: -1
  },
  methods: {
    // 长按开始拖动
    async onLongPress(e: WechatMiniprogram.TouchEvent) {
      const index = e.currentTarget.dataset.index;
      if (this.data.images.length <= 1) return; // 只有一张图片时不允许拖动
      
      // 获取触摸位置
      const touch = e.touches[0];
      const startX = touch.clientX;
      const startY = touch.clientY;
      
      // 标记当前拖动的图片
      this.setData({
        draggingIndex: index,
        tempImages: [...this.data.images],
        startX,
        startY,
        currentTargetIndex: index
      });
      
      // 添加拖动样式
      await this.sleep(300); // 等待长按确认时间
      if (this.data.draggingIndex !== -1) {
        this.setData({
          [`tempImages[${index}].dragging`]: true
        });
      }
    },
    
    // 触摸移动处理
    async onTouchMove(e: WechatMiniprogram.TouchEvent) {
      const { draggingIndex, tempImages, startX, startY } = this.data;
      if (draggingIndex === -1) return;
      
      const touch = e.touches[0];
      const moveX = touch.clientX;
      const moveY = touch.clientY;
      
      // 获取当前触摸的图片索引
      const targetIndex = await this.getTargetIndex(moveX, moveY);
      if (targetIndex !== -1 && targetIndex !== draggingIndex && targetIndex !== this.data.currentTargetIndex) {
        // 交换图片位置
        const newImages = [...tempImages];
        
        // 移除原位置的拖动样式
        newImages[draggingIndex].dragging = false;
        
        // 交换元素
        const draggedItem = newImages.splice(draggingIndex, 1)[0];
        newImages.splice(targetIndex, 0, draggedItem);
        
        // 添加新位置的拖动样式
        newImages[targetIndex].dragging = true;
        
        this.setData({
          tempImages: newImages,
          currentTargetIndex: targetIndex
        });
      }
    },
    
    // 触摸结束
    onTouchEnd() {
      if (this.data.draggingIndex !== -1) {
        // 移除拖动样式
        const tempImages = [...this.data.tempImages];
        tempImages[this.data.currentTargetIndex].dragging = false;
        
        this.triggerEvent('sort', { images: tempImages });
        this.setData({
          draggingIndex: -1,
          currentTargetIndex: -1
        });
      }
    },
    
    // 获取目标位置的图片索引
    getTargetIndex(x: number, y: number): Promise<number> {
      return new Promise(resolve => {
        const query = this.createSelectorQuery();
        query.selectAll('.image-item').boundingClientRect(rects => {
          if (!rects || rects.length === 0) {
            resolve(-1);
            return;
          }
          
          for (let i = 0; i < rects.length; i++) {
            const rect = rects[i];
            if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
              resolve(i);
              return;
            }
          }
          resolve(-1);
        }).exec();
      });
    },
    
    // 删除图片
    onDelete(e: WechatMiniprogram.TouchEvent) {
      if (!this.data.deletable) return;
      
      const index = e.currentTarget.dataset.index;
      this.triggerEvent('delete', { index });
    },
    
    // 工具函数：延迟执行
    sleep(ms: number) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
  },
  
  // 生命周期函数
  lifetimes: {
    attached() {
      // 初始化图片数据
      this.setData({
        tempImages: this.data.images.map(img => ({...img, dragging: false}))
      });
    }
  }
})